package chapter03

/**
 * author: yuhui
 * descriptions:
 * date: 2024 - 12 - 23 8:03 下午
 */
// 定义命令接口
trait Command {
  def execute(): Unit
}

// 定义接收者，即执行具体操作的类
trait Worker {
  def work(): Unit
}

// 具体的接收者实现
class JavaWorker extends Worker {
  override def work(): Unit = println("我是一个Java工程师")
}

class PhpWorker extends Worker {
  override def work(): Unit = println("我是一个PHP工程师")
}

class ScalaWorker extends Worker {
  override def work(): Unit = println("我是一个Spark工程师")
}

// 具体的命令实现，每个命令都封装了对一个接收者的调用
class JavaCommand(private val worker: Worker) extends Command {
  override def execute(): Unit = worker.work()
}

class PhpCommand(private val worker: Worker) extends Command {
  override def execute(): Unit = worker.work()
}

class ScalaCommand(private val worker: Worker) extends Command {
  override def execute(): Unit = worker.work()
}

// Invoker，负责调用命令
object Invoker {
  def executeCommand(command: Command): Unit = {
    command.execute()
  }
}

// Client，创建具体的命令对象，并设置命令的接收者，然后交给Invoker执行
object CommandPatternDemo {
  def main(args: Array[String]): Unit = {
    val javaWorker = new JavaWorker
    val javaCommand = new JavaCommand(javaWorker)
    Invoker.executeCommand(javaCommand)

    val phpWorker = new PhpWorker
    val phpCommand = new PhpCommand(phpWorker)
    Invoker.executeCommand(phpCommand)

    val scalaWorker = new ScalaWorker
    val scalaCommand = new ScalaCommand(scalaWorker)
    Invoker.executeCommand(scalaCommand)

    // 示例：如果需要一个未知命令的处理
    val unknownCommand = new Command {
      override def execute(): Unit = println("I don't know your job")
    }
    Invoker.executeCommand(unknownCommand)
  }
}